<?php
/**
 * Created by PhpStorm.
 * User: LFL
 * Date: 2010/5/25
 * Time: 16:02
 */
namespace api\controllers;

use Yii;
use common\helps\tools;
use yii\web\Controller;
use backend\models\Materiel;

class InventoryController extends Controller
{
    //物料+产品数据
    public function actionDataList()
    {
        $data = Yii::$app->request->post();

        $sql_pro = 'SELECT pc.name typeName, pm.name, pm.AutoId id FROM `product_master` pm LEFT JOIN `product_category` pc ON pm.categoryId=pc.categoryId WHERE pm.countFlg=1 ORDER BY pc.sort,pm.sort';
        $sql_mat = 'SELECT jw.`warehouseName` typeName,jm.`materielName` name,jm.id,jm.specDesc, jm.packDesc, jm.useDesc, jm.ext1 FROM `j_materiel` jm LEFT JOIN j_warehouse jw ON jm.`warehouseId`=jw.`id` WHERE jm.countFlg=1 ';
        if (isset($data['shopId']) && !empty($data['shopId'])) {
            $sql_mat .= ' AND (jm.shopId is null OR find_in_set(' . $data['shopId'] . ',jm.shopId))';
        }
        $sql_mat .= 'ORDER BY jm.warehouseId,jm.sort DESC';
        $list_pro = Yii::$app->db_assemble->createCommand($sql_pro)->queryAll();
        $list_mat = Yii::$app->db->createCommand($sql_mat)->queryAll();
        $result = array(
            'pro' => $list_pro,
            'mat' => $list_mat
        );

        $this->retJson('', 200, $result);
    }

    //新增、编辑模版
    public function actionAddTemplate()
    {
        $data = Yii::$app->request->post();

        if (!isset($data['userId']) || empty($data['userId']) ||
            !isset($data['shopId']) || empty($data['shopId']) ||
            !isset($data['tempName']) || empty($data['tempName']) ||
            !isset($data['data']) || !is_array($data['data'])
        ) {
            $this->retJson('参数错误', 500);
        }

        //商品
        $nowTime = date('Y-m-d H:i:s');
        foreach ($data['data'] as $res) {
            $itemArr[] = array(
                'type' => isset($res['type']) ? $res['type'] : 0,
                'resId' => $res['id'],
                'creator' => $data['userId'],
                'createTime' => $nowTime,
                'updator' => $data['userId'],
                'updateTime' => $nowTime
            );
        }

        $template = array(
            'name' => $data['tempName'],
            'shopId' => $data['shopId'],
            'remark' => isset($data['remark']) ? $data['remark'] : ''
        );

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (isset($data['tempId']) && !empty($data['tempId'])) {
                $tempId = $data['tempId'];
                $delSql = "DELETE FROM j_count_template_item WHERE templateId=" . $tempId;
                Yii::$app->db->createCommand($delSql)->execute();

                $template['updator'] = $data['userId'];
                $template['updateTime'] = $nowTime;
                Yii::$app->db->createCommand()->update('j_count_template', $template, ['id' => $tempId])->execute();
            } else {

                $template['creator'] = $data['userId'];
                $template['createTime'] = $nowTime;
                $template['updator'] = $data['userId'];
                $template['updateTime'] = $nowTime;
                Yii::$app->db->createCommand()->insert('j_count_template', $template)->execute();
                $tempId = Yii::$app->db->getLastInsertId();
            }

            //添加明细
            foreach ($itemArr as $item) {
                $item['templateId'] = $tempId;
                Yii::$app->db->createCommand()->insert('j_count_template_item', $item)->execute();
            }

            $transaction->commit();
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }

    //删除模版
    public function actionDelTemp()
    {
        $data = Yii::$app->request->post();
        $delSql = "DELETE FROM j_count_template WHERE id=" . $data['tempId'];
        Yii::$app->db->createCommand($delSql)->execute();
        $this->retJson('', 200);
    }

    //模版列表
    public function actionTempList()
    {
        $data = Yii::$app->request->post();
        $sql = 'SELECT cm.*, js.ShopName FROM j_count_template cm inner join j_shop js on cm.shopId=js.ShopID WHERE 1=1 ';
        if (isset($data['shopId']) && !empty($data['shopId'])) {
            $sql .= ' AND cm.shopId IN(' . $data['shopId'] . ')';
        }
//        if (isset($data['creator']) && !empty($data['creator'])) {
//            $sql .= " AND creator = '" . $data['creator'] . "'";
//        }
        $sql .= ' ORDER BY cm.updateTime DESC';
        $list = Yii::$app->db->createCommand($sql)->queryAll();
        $this->retJson('', 200, $list);
    }

    //模版详情
    public function actionTempDtl()
    {
        $data = Yii::$app->request->post();
        $sql = 'SELECT type,resId FROM j_count_template_item WHERE templateId = ' . $data['tempId'];
        $list = Yii::$app->db->createCommand($sql)->queryAll();
        $this->retJson('', 200, $list);
    }

    //盘点
    public function actionCountDtl()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['templateId']) || empty($data['templateId'])) {
            $this->retJson('参数错误', 500);
        }

        $returnArr = array();
        $today = date('Ymd');
        $templateId = $data['templateId'];

        $sql = 'select shopId from j_count_template where id=' . $templateId;
        $shopRes = Yii::$app->db->createCommand($sql)->queryOne();

        $sql = "SELECT id,templateId FROM j_count_sheet WHERE shopId = " . $shopRes['shopId'] . " AND code='" . $today . "'";
        $sheet = Yii::$app->db->createCommand($sql)->queryOne();
        if ($sheet && $sheet['templateId'] == $templateId) {
            $sql_c = 'select type,resId,qty from j_count_sheet_item where countId=' . $sheet['id'];
            $list_c = Yii::$app->db->createCommand($sql_c)->queryAll();
            //type 1:物料 2:内部产品
            foreach ($list_c as $c) {
                $type = $c['type'] == 1 ? 'mat' : 'pro';
                $returnArr[$type][$c['resId']] = array(
                    'resId' => $c['resId'],
                    'type' => $c['type'],
                    'qty' => $c['qty'],
                );
            }
        }

        $sql_t = 'select type,resId from j_count_template_item where templateId=' . $templateId;
        $list_t = Yii::$app->db->createCommand($sql_t)->queryAll();
        //type 1:物料 2:内部产品
        foreach ($list_t as $t) {
            $type = $t['type'] == 1 ? 'mat' : 'pro';
            if (isset($returnArr[$type][$t['resId']]))
                continue;

            $returnArr[$type][$t['resId']] = array(
                'resId' => $t['resId'],
                'type' => $t['type'],
                'qty' => 0
            );
        }

        foreach ($returnArr as $type => &$fa) {
            foreach ($fa as &$val) {
                if ($type == 'mat') {
                    $sql = 'SELECT jw.`warehouseName` categoryName ,jm.`materielName` name,jm.specDesc, jm.packDesc, jm.useDesc, jm.ext1 FROM `j_materiel` jm LEFT JOIN j_warehouse jw ON jm.`warehouseId`=jw.`id` WHERE jm.id=' . $val['resId'];
                    $res = Yii::$app->db->createCommand($sql)->queryOne();
                    $val['specDesc'] = $res['specDesc'];
                    $val['packDesc'] = $res['packDesc'];
                    $val['useDesc'] = $res['useDesc'];
                    $val['ext1'] = $res['ext1'];
                }
                if ($type == 'pro') {
                    $sql = 'SELECT pc.name categoryName, pm.name FROM `product_master` pm LEFT JOIN `product_category` pc ON pm.categoryId=pc.categoryId WHERE pm.AutoId = ' . $val['resId'];
                    $res = Yii::$app->db_assemble->createCommand($sql)->queryOne();
                }
                $val['name'] = $res['name'];
                $val['categoryName'] = $res['categoryName'];
            }
        }
        $returnArr['countId'] = $sheet ? $sheet['id'] : null;
        $this->retJson('', 200, $returnArr);
    }

    //保存盘点数据
    public function actionAddCount()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['userId']) || empty($data['userId']) ||
            !isset($data['templateId']) || empty($data['templateId'])
        ) {
            $this->retJson('参数错误', 500);
        }

        $code = date('Ymd');
        $nowTime = date('Y-m-d H:i:s');

        //保存时间不可以超过24点
        if (isset($data['countId']) && !empty($data['countId'])) {
            $sql = 'SELECT code FROM j_count_sheet WHERE  id= ' . $data['countId'];
            $res = Yii::$app->db->createCommand($sql)->queryOne();
            if ($code != $res['code']) {
                $this->retJson('当天盘点已结束，请重新操作', 500);
            }
        }

        $sql = 'select shopId from j_count_template where id=' . $data['templateId'];
        $shopRes = Yii::$app->db->createCommand($sql)->queryOne();

        $count = array(
            'code' => $code,
            'templateId' => $data['templateId'],
            'shopId' => $shopRes['shopId'],
            'remark' => isset($data['remark']) ? $data['remark'] : null
        );

        $itemArr = array();
        if (isset($data['data']) && is_array($data['data'])) {
            foreach ($data['data'] as $res) {
                $itemArr[] = array(
                    'type' => isset($res['type']) ? $res['type'] : 0,
                    'resId' => $res['id'],
                    'qty' => $res['qty'],
                    'creator' => $data['userId'],
                    'createTime' => $nowTime,
                    'updator' => $data['userId'],
                    'updateTime' => $nowTime
                );
            }
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (isset($data['countId']) && !empty($data['countId'])) {
                $countId = $data['countId'];
                $delSql = "DELETE FROM j_count_sheet_item WHERE countId=" . $countId;
                Yii::$app->db->createCommand($delSql)->execute();
                $count['updator'] = $data['userId'];
                $count['updateTime'] = $nowTime;
                Yii::$app->db->createCommand()->update('j_count_sheet', $count, ['id' => $countId])->execute();
            } else {
                $count['creator'] = $data['userId'];
                $count['createTime'] = $nowTime;
                Yii::$app->db->createCommand()->insert('j_count_sheet', $count)->execute();
                $countId = Yii::$app->db->getLastInsertId();
            }

            //添加明细
            foreach ($itemArr as $item) {
                $item['countId'] = $countId;
                Yii::$app->db->createCommand()->insert('j_count_sheet_item', $item)->execute();
            }

            $transaction->commit();
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }

    //损耗
    public function actionLossDtl()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['templateId']) || empty($data['templateId'])) {
            $this->retJson('参数错误', 500);
        }

        $returnArr = array();
        $today = date('Ymd');
        $templateId = $data['templateId'];

        $sql = 'select shopId from j_count_template where id=' . $templateId;
        $shopRes = Yii::$app->db->createCommand($sql)->queryOne();

        $sql = "SELECT id,templateId FROM j_loss_sheet WHERE shopId = " . $shopRes['shopId'] . " AND code='" . $today . "'";
        $sheet = Yii::$app->db->createCommand($sql)->queryOne();
        if ($sheet && $sheet['templateId'] == $templateId) {
            $sql_c = 'select type,resId,qty from j_loss_sheet_item where lossId=' . $sheet['id'];
            $list_c = Yii::$app->db->createCommand($sql_c)->queryAll();
            //type 1:物料 2:内部产品
            foreach ($list_c as $c) {
                $type = $c['type'] == 1 ? 'mat' : 'pro';
                $returnArr[$type][$c['resId']] = array(
                    'resId' => $c['resId'],
                    'type' => $c['type'],
                    'qty' => $c['qty'],
                );
            }
        }

        $sql_t = 'select type,resId from j_count_template_item where templateId=' . $templateId;
        $list_t = Yii::$app->db->createCommand($sql_t)->queryAll();
        //type 1:物料 2:内部产品
        foreach ($list_t as $t) {
            $type = $t['type'] == 1 ? 'mat' : 'pro';
            if (isset($returnArr[$type][$t['resId']]))
                continue;

            $returnArr[$type][$t['resId']] = array(
                'resId' => $t['resId'],
                'type' => $t['type'],
                'qty' => 0
            );
        }

        foreach ($returnArr as $type => &$fa) {
            foreach ($fa as &$val) {
                if ($type == 'mat') {
                    $sql = 'SELECT jw.`warehouseName` categoryName ,jm.`materielName` name,jm.specDesc, jm.packDesc, jm.useDesc, jm.ext1 FROM `j_materiel` jm LEFT JOIN j_warehouse jw ON jm.`warehouseId`=jw.`id` WHERE jm.id=' . $val['resId'];
                    $res = Yii::$app->db->createCommand($sql)->queryOne();
                    $val['specDesc'] = $res['specDesc'];
                    $val['packDesc'] = $res['packDesc'];
                    $val['useDesc'] = $res['useDesc'];
                    $val['ext1'] = $res['ext1'];
                }
                if ($type == 'pro') {
                    $sql = 'SELECT pc.name categoryName, pm.name FROM `product_master` pm LEFT JOIN `product_category` pc ON pm.categoryId=pc.categoryId WHERE pm.AutoId = ' . $val['resId'];
                    $res = Yii::$app->db_assemble->createCommand($sql)->queryOne();
                }
                $val['name'] = $res['name'];
                $val['categoryName'] = $res['categoryName'];
            }
        }
        $returnArr['lossId'] = $sheet ? $sheet['id'] : null;
        $this->retJson('', 200, $returnArr);
    }

    //保存损耗数据
    public function actionAddLoss()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['userId']) || empty($data['userId']) ||
            !isset($data['templateId']) || empty($data['templateId'])
        ) {
            $this->retJson('参数错误', 500);
        }

        $code = date('Ymd');
        $nowTime = date('Y-m-d H:i:s');

        //保存时间不可以超过24点
        if (isset($data['lossId']) && !empty($data['lossId'])) {
            $sql = 'SELECT code FROM j_loss_sheet WHERE  id= ' . $data['lossId'];
            $res = Yii::$app->db->createCommand($sql)->queryOne();
            if ($code != $res['code']) {
                $this->retJson('当天盘点已结束，请重新操作', 500);
            }
        }

        $sql = 'select shopId from j_count_template where id=' . $data['templateId'];
        $shopRes = Yii::$app->db->createCommand($sql)->queryOne();

        $count = array(
            'code' => $code,
            'templateId' => $data['templateId'],
            'shopId' => $shopRes['shopId'],
            'remark' => isset($data['remark']) ? $data['remark'] : null
        );

        $itemArr = array();
        if (isset($data['data']) && is_array($data['data'])) {
            foreach ($data['data'] as $res) {
                $itemArr[] = array(
                    'type' => isset($res['type']) ? $res['type'] : 0,
                    'resId' => $res['id'],
                    'qty' => $res['qty'],
                    'creator' => $data['userId'],
                    'createTime' => $nowTime,
                    'updator' => $data['userId'],
                    'updateTime' => $nowTime
                );
            }
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (isset($data['lossId']) && !empty($data['lossId'])) {
                $lossId = $data['lossId'];
                $delSql = "DELETE FROM j_loss_sheet_item WHERE lossId=" . $lossId;
                Yii::$app->db->createCommand($delSql)->execute();
                $count['updator'] = $data['userId'];
                $count['updateTime'] = $nowTime;
                Yii::$app->db->createCommand()->update('j_loss_sheet', $count, ['id' => $lossId])->execute();
            } else {
                $count['creator'] = $data['userId'];
                $count['createTime'] = $nowTime;
                Yii::$app->db->createCommand()->insert('j_loss_sheet', $count)->execute();
                $lossId = Yii::$app->db->getLastInsertId();
            }

            //添加明细
            foreach ($itemArr as $item) {
                $item['lossId'] = $lossId;
                Yii::$app->db->createCommand()->insert('j_loss_sheet_item', $item)->execute();
            }

            $transaction->commit();
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }
}